package com.zwj.gateway;

import org.springframework.http.HttpHeaders;
import org.springframework.web.server.ServerWebExchange;
import java.util.Objects;

public class RemoteIP {

    public static String getRemoteIP(ServerWebExchange exchange) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String remoteAddress = headers.getFirst("X-Forwarded-For");
        if (remoteAddress == null || remoteAddress.isEmpty() || "unknown".equalsIgnoreCase(remoteAddress)) {
            remoteAddress = headers.getFirst("Proxy-Client-IP");
        }
        if (remoteAddress == null || remoteAddress.isEmpty() || "unknown".equalsIgnoreCase(remoteAddress)) {
            remoteAddress = headers.getFirst("WL-Proxy-Client-IP");
        }
        if (remoteAddress == null || remoteAddress.isEmpty() || "unknown".equalsIgnoreCase(remoteAddress)) {
            remoteAddress = headers.getFirst("HTTP_CLIENT_IP");
        }
        if (remoteAddress == null || remoteAddress.isEmpty() || "unknown".equalsIgnoreCase(remoteAddress)) {
            remoteAddress = headers.getFirst("HTTP_X_FORWARDED_FOR");
        }
        if (remoteAddress == null || remoteAddress.isEmpty() || "unknown".equalsIgnoreCase(remoteAddress)) {
            remoteAddress = Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getAddress().getHostAddress();
        }
        // remoteAddress 变量中保存了远程IP
        return remoteAddress;
    }
}
